/**
 * 
 */
package com.p2p.base.interceptors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.MDC;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import com.p2p.base.model.BaseUser;
import com.p2p.base.util.LoginUtil;

/**
 * @author ruiqi
 *
 */
public class LogMDCInterceptor extends HandlerInterceptorAdapter{

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		
		if (handler instanceof ResourceHttpRequestHandler) {
			return true;
		}
		BaseUser user = (BaseUser)LoginUtil.getCurrentUser();
		
		if(user!=null){
			String id = user.getId();
			String name = user.getName();
			MDC.put("loginUser", "uid:"+id+"@"+name);
		}
		String ip = LoginUtil.getRemoteIp(request); 
		MDC.put("userip", ip);
		return true;
	}
	
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
		super.postHandle(request, response, handler, modelAndView);
	}
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		MDC.remove("loginName");
		MDC.remove("userip");
		super.afterCompletion(request, response, handler, ex);
	}
}
